﻿using AutoMapper;
using B.S.DataBase.Domain;
using B.S.DataBase.ErrorCode;
using B.S.DataBase.Infrastructure;
using B.S.DataBase.Write.API.Application.Commands;
using MediatR;

namespace B.S.DataBase.Write.API.Application.Handlers
{
    public class CreateProductTypeHandler : IRequestHandler<CreateProductTypeCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ProductType> productTypeRepository;
        private readonly IMapper mapper;

        public CreateProductTypeHandler(IBaseRepository<ProductType> productTypeRepository, IMapper mapper)
        {
            this.productTypeRepository = productTypeRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(CreateProductTypeCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            var entity = mapper.Map<ProductType>(request);

            var res = productTypeRepository.GetAllAsync().Where(x => x.ProductName == request.ProductName).Count();
            if (res > 0)
            {
                result.Code = APIEnums.Fail;
                result.Meg = "商品名称重复";
                return await Task.FromResult(result);
            }

            var dto = productTypeRepository.AddAsync(entity).Result;
            if (dto > 0)
            {
                result.Code = APIEnums.Success;
                result.Meg = "新增成功";
                result.Data = dto;
            }
            else
            {
                result.Code = APIEnums.Fail;
                result.Meg = "新增失败";
                return await Task.FromResult(result);
            }

            return await Task.FromResult(result);
        }
    }
}
